package com.w08e.waai;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkrobot_1_0.Client;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: 梦想成为超人的猪猪侠
 * @Date: 2025/3/20 10:06
 */
@Slf4j
public class SendGroupMessage {

    private static final String CLIENT_ID = "dingdccijs9wyugmlyfc";
    private static final String CLIENT_SECRET = "LHWcWqN9lNNJr6fT7_Q4XkA3XxUfvdDSbBonhRYFMB_TVxipDSxIZpKujrSdbBsx";

    public static void main(String[] args) {
        // 需要提前获取的固定参数（需替换为实际值）
        String targetConversationId = "cidWkB3dR7UvwY0oScabFsctg==";
        String robotCode = "dingdccijs9wyugmlyfc";

        // 发送主动消息 并对消息换行

        sendActiveGroupMessage(targetConversationId, robotCode, "大饼出现买入：,\n" +
                "买入价格：,\n" + "买入时间：,\n" + "买入数量：,\n" + "买入金额：,\n" + "买入手续费：,\n" + "买入备注：,\n" + "买入人：,\n" + "买入人联系方式：,\n" + "买入人备注：,\n" + "买入人所在地：,\n" + "买入人所在地备注：,\n" + "买入人所在地联系方式");
    }

    /**
     * 主动发送群消息
     *
     * @param conversationId 群会话ID（通过其他接口获取）
     * @param robotCode      机器人编码
     * @param message        要发送的文本内容
     */
    public static void sendActiveGroupMessage(String conversationId, String robotCode, String message) {
        try {
            // 构造请求头
            OrgGroupSendHeaders headers = new OrgGroupSendHeaders();
            headers.setXAcsDingtalkAccessToken(getToken());

            // 构造消息体
            OrgGroupSendRequest request = new OrgGroupSendRequest()
                    .setMsgKey("sampleText")  // 消息模板类型
                    .setRobotCode(robotCode)
                    .setOpenConversationId(conversationId);

            JSONObject msgParam = new JSONObject();
            msgParam.put("content",  message);
            request.setMsgParam(msgParam.toJSONString());

            // 发送请求
            Client client = createRobotClient();
            OrgGroupSendResponse response = client.orgGroupSendWithOptions(
                    request, headers, new com.aliyun.teautil.models.RuntimeOptions());

            // 处理响应
            if (response != null && response.getBody() != null) {
                log.info("消息发送成功，response={}", JSONObject.toJSONString(response.getBody()));
            }
        } catch (Exception e) {
            log.error("主动消息发送失败", e);
        }
    }


    private static Client createRobotClient() throws Exception {
        Config config = new Config()
                .setProtocol("https")
                .setRegionId("central");
        return new Client(config);
    }

    public static String getToken() {
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest();
        getAccessTokenRequest.setAppKey(CLIENT_ID);
        getAccessTokenRequest.setAppSecret(CLIENT_SECRET);
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        try {
            com.aliyun.dingtalkoauth2_1_0.Client client = new com.aliyun.dingtalkoauth2_1_0.Client(config);
            GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
            return accessToken.getBody().getAccessToken();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
